<template>
  <el-select
    v-model="select"
    class="forminput"
    placeholder="请选择部门"
    :disabled="disabled"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.displayName"
      :value="item.id"
    />
  </el-select>
</template>

<script>
  import { getUserDeptListOptions as getAll } from '/src/api/workflow'
  import { copy } from '../../utils/jsex'

  export default {
    name: 'DeptSelect',
    props: {
      formData: {
        type: Object,
        default: function () {
          return {}
        },
      },
      // eslint-disable-next-line vue/require-default-prop,vue/require-prop-types
      selectData: {},
      disabled: {
        type: Boolean,
        default: function () {
          return false
        },
      },
      keyByLabelData: {
        type: String,
        default: function () {
          return 'deptName'
        },
      },
    },
    data() {
      return {
        options: [],
        select: copy(this.selectData),
      }
    },
    computed: {
      keyByLabel() {
        if (this.keyByLabelData) {
          return this.keyByLabelData
        } else {
          return 'deptName'
        }
      },
    },
    watch: {
      selectData: {
        handler: function (v) {
          this.select = copy(v)
        },
        deep: true,
        immediate: true,
      },
      select: {
        handler: function (v) {
          this.$emit('update:selectData', v)
          if (v !== undefined) {
            this.options.forEach((value) => {
              if (v === value.id) {
                let displayName = value.displayName
                let f = Object.assign({}, this.formData)
                f[this.keyByLabel] = displayName
                this.$emit('update:formData', f)
              }
            })
          }
        },
        deep: true,
        immediate: true,
      },
    },
    created() {
      this.fetchData()
    },
    methods: {
      async fetchData() {
        const resp = await getAll(this.formData.createuid)
        this.options = resp.data

        if (!this.selectData) {
          return
        }

        let add = true
        for (let option of this.options) {
          if (option.id === this.selectData) {
            add = false
            break
          }
        }
        if (add) {
          this.options = [
            {
              id: this.selectData,
              displayName: this.formData[this.keyByLabel],
            },
          ].concat(this.options)
        }
      },
    },
  }
</script>
